import mongoengine as db
import arrow

from app.db import BaseDocument
from app.libs.enums import ChargeType, LimitType


class Charges(BaseDocument):
    meta = {
        'strict': False,
        'collection': 'charges',
    }

    limitType = db.StringField(default='limit', choices=[item.value for item in LimitType])
    used = db.IntField(min_value=0, default=0)
    total = db.LongField(min_value=0, default=0)
    number = db.IntField(min_value=0, default=0)
    funcType = db.StringField(default='')
    packId = db.ObjectIdField()
    uid = db.ObjectIdField()
    chargeType = db.StringField(default='', choices=[item.value for item in ChargeType])
    time = db.LongField(min_value=0, default=0)
    createTime = db.DateTimeField()
    updateTime = db.DateTimeField()
    expireTime = db.DateTimeField()
    taskType = db.StringField(default='')
    isDelete = db.BooleanField(default=False)

    def save(self, *args, **kwargs):
        now_datetime = arrow.utcnow().datetime
        if not self.createTime:
            self.createTime = now_datetime
        self.updateTime = now_datetime
        return super(Charges, self).save(*args, **kwargs)

    def update(self, **kwargs):
        kwargs['updateTime'] = arrow.utcnow().datetime
        return super(Charges, self).update(**kwargs)
